﻿
@{
    ViewData["Title"] = "Index";
}

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="~/lib/element-ui/index.js"></script>
<link href="~/lib/element-ui/theme-chalk/index.css" rel="stylesheet" />
<div id="app" class="" style="line-height:35px;width:850px;margin:10px auto;">
    @*<div style="padding:10px">
            <el-select v-model="selectFile" style="width:300px;" placeholder="单选框" @@change="jobExperienceChange">
                <el-option label="主线" value="1"></el-option>
                <el-option label="新开发" value="2"></el-option>
            </el-select>
        </div>*@
    <div style="padding:10px">
        <el-select v-model="selectSite" style="width:600px;" placeholder="多选框" multiple>
            <el-option v-for="(item,key) in options" :key="key" :label="item.Id" :value="item.Name"></el-option>
        </el-select>
    </div>

    <div style="padding:10px">
        生成代码并上传到服务器
        <input id="btn_starBuild" type="button" width="50" v-on:click="starUpload" value="开始上传" />
    </div>
    <div style="padding:30px">

        <div style="padding:10px" v-html="message_loadSite">
        </div>

    </div>
    <div style="padding:10px" v-html="message">

    </div>

    <div id="loadingWrap" v-if="loading">
        <div class="loading">
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
        </div>
        <div class="loadingTxt" v-html="loadingTxt"></div>
    </div>
</div>

<style>
    #loadingWrap {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 111;
        background: rgba(255,255,255,0.4);
    }

    .loading {
        width: 120px;
        height: 15px;
        margin: 0 auto;
        margin-top: 130px;
    }

    .loadingTxt {
        width: 500px;
        line-height: 40px;
        height: 40px;
        margin: 0 auto;
        text-align: center;
        overflow: hidden;
        padding-top: 10px;
    }

    .loading span {
        display: inline-block;
        width: 15px;
        height: 100%;
        margin-right: 5px;
        border-radius: 50%;
        background: #f60;
        -webkit-animation: load 1.04s ease infinite;
    }

        .loading span:last-child {
            margin-right: 0px;
        }

    @@-webkit-keyframes load {
        0% {
            opacity: 1;
            -webkit-transform: scale(1.3);
        }

        100% {
            opacity: 0.2;
            -webkit-transform: scale(.3);
        }
    }

    .loading span:nth-child(1) {
        -webkit-animation-delay: 0.13s;
    }

    .loading span:nth-child(2) {
        -webkit-animation-delay: 0.26s;
    }

    .loading span:nth-child(3) {
        -webkit-animation-delay: 0.39s;
    }

    .loading span:nth-child(4) {
        -webkit-animation-delay: 0.52s;
    }

    .loading span:nth-child(5) {
        -webkit-animation-delay: 0.65s;
    }
</style>

<script type="text/javascript">
    var app = new Vue({
        el: '#app',
        data: {
            mymsg:"my",
            message: "by chenjie 2020.03.31",
            message_loadSite: "",
            key: "",
            selectSite: [],
            selectFile:"",
            autoStopAndStart: true,
            clearAllFiles: false,
            autoUncompress: false,
            uploadFiles: [],
            webSites: [],
            selectSite2: "",
            loading: false,
            loadingTxt: "正在获取全部的站点数据",
            options: [],
            flag: false,
            urls:"",
        },
        //created: function () {
        //    var _webSites = JSON.parse(localStorage.getItem("_webSites"))
        //    if (!_webSites || _webSites.length <= 0) {
        //        this.getAllSite();
        //    }
        //    this.webSites = _webSites;
        //},
        created: function () {
            this.getAllSite();
        },
        methods: {
            getAllSite: function () {
                let that = this;
                this.showMessage(`正在获取全部的站点数据`);
                that.showLoading(true, "");
                axios.post('/UploadFiles/GetAllSite')
                    .then(function (response) {
                        that.showLoading(false, "");
                        that.webSites = response.data;
                        for (var i = 0; i < response.data.length; i++) {
                         
                            var json = { "Id": response.data[i], "Name": response.data[i] };
                            that.options.push(json);
                        }

                        //localStorage.setItem("_webSites", JSON.stringify(response.data));
                        that.showMessage(`全部站点获取完成，共获取了${that.webSites.length}个站点。`);
                    })
                    .catch(function (error) {
                        that.showLoading(false, "");
                        that.showMessage(error);
                    });

            },
            jobExperienceChange: function () {
                let that = this;
                this.showMessage(`正在获取全部的站点数据`);
                that.showLoading(true, "");
                axios.post('/UploadFiles/GetAllSite', {
                    file: that.selectFile
                })
                    .then(function (response) {
                        that.showLoading(false, "");
                        that.webSites = response.data;
                        for (var i = 0; i < response.data.length; i++) {
                            debugger;
                            var json = { "Id": response.data[i], "Name": response.data[i] };
                            that.options.push(json);
                        }

                        //localStorage.setItem("_webSites", JSON.stringify(response.data));
                        that.showMessage(`全部站点获取完成，共获取了${that.webSites.length}个站点。`);
                    })
                    .catch(function (error) {
                        that.showLoading(false, "");
                        that.showMessage(error);
                    });
            },
            starUpload () {
              
                let that = this;
                that.flag = false;
             
                let t= setInterval(function () {
                  
                    if (that.flag) {
                     
                        clearInterval(t);
                    }
                    else {
                        that.test();
                    }
                }, 1000)
                this.showMessage(`正在编译站点并发布到测试服务器`);
                that.showLoading(true, "");
                axios.post('/UploadFiles/UpLoadFiles',
                    that.selectSite
                ).then(function (response) {                 
                        that.flag = true;
                        that.showLoading(false, "");
                        //that.webSites = response.data;
                        //localStorage.setItem("_webSites", JSON.stringify(response.data));
                    var msg = response.data.split('%')[0];
                    that.showMessage(msg);
                        var baseUrl = response.data.split('%')[1];
                        that.goTo(baseUrl);
                    })
                    .catch(function (error) {
                        that.flag = true;
                        that.showLoading(false, "");
                        that.showMessage(error);
                    });
            },
            time() {
               },
            test: function () {
                let that = this;
                axios.post('/UploadFiles/GetMsg').then(function (response) {
                    var msg = response.data;
                    debugger;
                    //console.log(msg);
                    that.showMessage(msg);
                    //that.showMessage(response.data);
                }).catch(function (error) {
                    var msg = error;
                    that.showMessage(msg);
                })
            },
            goTo: function (e) {
                let that = this;
                
                that.selectSite.map(oo => {
                    let url = "";
                    url = e + ':' + oo.split(':')[1] + '/swagger/index.html';
                    url = "<a target='_blank' href='" + url + "'>" + oo + " swagger</a></br>"
                    debugger;
                    that.urls += "   " + url;
                    //window.open(url, '_blank ');
                    that.showMessageLoadSite(that.urls);
                })
            },
            stopSite: function (isUpload) {
                if (!this.selectSite) {
                    this.showMessage(`请选择一个站点`);
                    return;
                }
                let that = this;
                that.showLoading(true, "");
                this.showMessage(`停止站点${this.selectSite}中...`);
                axios.post('/Home/StopSite', {
                    website: that.selectSite,
                    key: this.key
                })
                    .then(function (response) {
                        that.showLoading(false, "");
                        that.showMessage(response.data);
                        if (typeof (isUpload) != "undefined" && isUpload) {
                            that.uploadFileNow();
                        }
                    })
                    .catch(function (error) {
                        that.showLoading(false, "");
                        that.showMessage(error);
                    });
            },
            startSite: function () {
                if (!this.selectSite) {
                    this.showMessage(`请选择一个站点`);
                    return;
                }
                let that = this;
                that.showLoading(true, "");
                this.showMessage(`开启站点${this.selectSite}中...`);
                axios.post('/Home/StartSite', {
                    website: this.selectSite,
                    key: this.key
                })
                    .then(function (response) {
                        that.showLoading(false, "");
                        that.showMessage(response.data);
                        that.loadSite(this.selectSite);
                    })
                    .catch(function (error) {
                        that.showLoading(false, "");
                        that.showMessage(error);
                    });
            },
            copySite: function () {
                if (!this.selectSite) {
                    this.showMessage(`请选择一个站点`);
                    return;
                }
                if (!this.selectSite2) {
                    this.showMessage(`请选择目标站点`);
                    return;
                }
                let that = this;
                that.showLoading(true, "");
                this.showMessage(`复制站点${this.selectSite}中...`);
                axios.post('/Home/CopySite', {
                    website: this.selectSite,
                    website2: this.selectSite2,
                    key: this.key
                })
                    .then(function (response) {
                        that.showLoading(false, "");
                        that.showMessage(response.data);
                        that.loadSite(this.selectSite2);
                    })
                    .catch(function (error) {
                        that.showLoading(false, "");
                        that.showMessage(error);
                    });
            },
            exportSite: function () {
                let that = this;
                that.showLoading(true, "正在导出站点数据...");
                axios.post('/Home/ExportSite', {})
                    .then(function (response) {
                        that.showLoading(false, "");
                        that.showMessage("导出完成。");
                    })
                    .catch(function (error) {
                        that.showLoading(false, "");
                        that.showMessage(error);
                    });
            },
            downloadSiteLog: function () {
                if (!this.selectSite) {
                    this.showMessage(`请选择一个站点`);
                    return;
                }
                let that = this;
                that.showLoading(true, "正在下载当天日志...");
                axios.post('/Home/DownloadSiteLog', {
                    website: this.selectSite,
                    website2: this.selectSite2,
                    key: this.key
                },
                    {
                        responseType: 'arraybuffer'
                    })
                    .then(function (response) {
                        that.showLoading(false, "");
                        that.showMessage("导出当天日志完成。");
                        that.download(response.data, `${that.selectSite}_log.zip`);
                    })
                    .catch(function (error) {
                        that.showLoading(false, "");
                        that.showMessage(error);
                    });
            },
            loadSite: function (site) {
                let that = this;
                var host = location.host.split(":")[0];
                if (typeof (site) == "undefined" || !site) {
                    site = this.selectSite;
                }
                if (site) {
                    that.showLoading(true, "");
                    var portList = this.webSites.filter(q => q.indexOf(site + ":") >= 0);
                    var port = 0;
                    if (portList && portList.length > 0) { port = portList[0].split(":")[1]; }
                    if (port) {
                        that.showMessageLoadSite(`Loading ${host}:${port}/swagger/index.html`);
                        axios.get(`http://${host}:${port}/swagger/index.html`, {})
                            .then(function (response) {
                                that.showLoading(false, "");
                                if (response.data.indexOf("swagger") > 0) {
                                    that.showMessageLoadSite(`站点请求成功，<a target='_blank' href='http://${host}:${port}/swagger/index.html'>${site} swagger</a>`);
                                }
                                else {
                                    that.showMessageLoadSite(response.data);
                                }
                            })
                            .catch(function (error) {
                                that.showLoading(false, "");
                                that.showMessageLoadSite(`${error}，<a target='_blank' href='http://${host}:${port}/swagger/index.html'>${site} swagger</a>`);
                            });
                    }
                    else {
                        that.showMessageLoadSite("未找到站点的的可访问端口");
                    }
                }
            },
            fileChange: function (e) {
                let $target = e.target || e.srcElement
                this.uploadFiles = $target.files;
                if (this.uploadFiles.length >= 0) {
                    var file = this.uploadFiles[0];
                    if (file.name.substring(file.name.lastIndexOf(".") + 1) == "zip") {
                        this.clearAllFiles = true;
                        this.autoUncompress = true;
                    }
                    else {
                        this.clearAllFiles = false;
                        this.autoUncompress = false;
                    }
                }
            },
            selectSiteChange: function (e) {
                this.selectSite2 = "";
                var arr = this.selectSite.split('.');
                if (arr.length > 1) {
                    for (var i = 0; i < this.webSites.length; i++) {
                        var site = this.webSites[i].split(':')[0];
                        var arr2 = site.split('.');
                        if (arr2.length > 1 && arr2[0] == "HysHyyx" && arr2[1] == arr[1]) {
                            this.selectSite2 = site;
                            break;
                        }
                    }
                }
                var portList = this.webSites.filter(q => q.indexOf(this.selectSite + ":") >= 0);
                var port = 0;
                if (portList && portList.length > 0) { port = portList[0].split(":")[1]; }
                if (port) {
                    var host = location.host.split(":")[0];
                    this.showMessageLoadSite(`<a target='_blank' href='http://${host}:${port}/swagger/index.html'>${this.selectSite} swagger</a>`);
                }
                //var file = document.getElementById("File1");
                //file.outerHTML = file.outerHTML;
            },
            selectSiteChanges: function (e) {
                var t = e;
                debugger;
            },
            uploadFile: function () {
                let that = this;
                if (!this.uploadFiles || this.uploadFiles.length <= 0) {
                    this.showMessage(`请选择待上传的文件`);
                    return;
                }
                if (this.autoStopAndStart) {
                    this.stopSite(1);
                }
                else {
                    this.uploadFileNow();
                }
            },
            uploadFileNow: function () {
                let that = this;
                if (this.uploadFiles.length <= 0) {
                    return;
                }
                this.showMessage(`开始上传，共准备上传${this.uploadFiles.length}个文件。`);
                that.showLoading(true, "");
                let okCount = 0, errorCount = 0, total = that.uploadFiles.length;
                for (var i = 0; i < total; i++) {
                    let file = this.uploadFiles[i];
                    let formData = new FormData();
                    formData.append("uploadFile", file, file.name);
                    formData.append("webSite", that.selectSite);
                    formData.append("key", that.key);
                    formData.append("index", i);
                    formData.append("clearAllFiles", that.clearAllFiles ? 1 : 0);
                    formData.append("autoUncompress", that.autoUncompress ? 1 : 0);

                    if (that.autoUncompress && file.name.substring(file.name.lastIndexOf(".") + 1) != "zip") {
                        that.showMessage("自动解压的文件必须是zip文件");
                        that.showLoading(false, "");
                        return;
                    }

                    const config = {
                        headers: { "Content-Type": "multipart/form-data;boundary=" + new Date().getTime() }
                    };
                    axios
                        .post("/Home/Upload", formData, config)
                        .then(function (response) {

                            if (response.data.indexOf("失败")) {
                                okCount++;
                            }
                            else {
                                errorCount++
                            }
                            that.showMessage(`<div>${file.name}：${response.data}</div>`, true);
                            if (okCount + errorCount == total) {
                                that.showLoading(false, "");
                                var msg = `<div>上传全部完成，共上传${okCount}/${total}，失败${errorCount}个文件</div>`;
                                that.showMessage(msg);
                                if (that.autoStopAndStart) {
                                    that.startSite();
                                }
                            }
                        })
                        .catch(function (error) {
                            errorCount++
                            var msg = `<div style="color:red">${file.name}：${error}</div>`
                            that.showMessage(msg, true);
                            if (okCount + errorCount == total) {
                                that.showLoading(false, "");
                                var msg = `<div>上传全部完成，共上传成功${okCount}/${total}个，失败${errorCount}个</div>`;
                                that.showMessage(msg, false, true);
                            }
                        })
                }
            },
            showMessage: function (msg, isAppend, isPre) {
                this.message = ((typeof isAppend == "undefined" || !isAppend) ? "" : this.message) + msg + ((typeof isPre == "undefined" || !isPre) ? "" : this.message);
                this.loadingTxt = msg;
            },
            showMessageLoadSite: function (msg, isAppend) {
                this.message_loadSite = ((typeof isAppend == "undefined" || !isAppend) ? "" : this.message) + msg;
                this.loadingTxt = msg;
            },
            showLoading: function (isShow, showTxt) {
                this.loading = isShow;
                this.loadingTxt = showTxt || "Loading...";
            },
            download: function (content, fileName) {
                const blob = new Blob([content], { type: "application/zip" });
                const a = document.createElement("a");
                const url = window.URL.createObjectURL(blob);
                const filename = fileName;
                a.href = url;
                a.download = filename;
                a.click();
                window.URL.revokeObjectURL(url);
            }
        }
    })
</script>


